package com.wyb.fastdfs.service;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wyb.fastdfs.entity.FileEntity;
import com.wyb.fastdfs.mapper.FileMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author:wangyibo
 * @Date 2021年8月10日
 * @Version:1.0
 * @Description:TODO
 */
@Service
@Slf4j
public class UploadService {
	@Autowired
	private FastFileStorageClient fastFileStorageClient;

	@Autowired
	private FileMapper fileMapper;

	@Value("${upload.base-url}")
	public String baseUrl;

	// 上传图片
	public String uploadImage(MultipartFile file) {
		try {
			// 校验文件
			BufferedImage image = ImageIO.read(file.getInputStream());
			if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
//				throw new RuntimeException("上传文件不是图片");
				return "上传文件不是图片";
			}
		} catch (IOException e) {
			// TODO: handle exception
			log.error("上传出错，校验文件内容失败...{}", e);
			return "上传出错，校验文件内容失败...{}";
//			throw new RuntimeException("校验文件内容失败" + e.getMessage());
		}

		try {
			// 获取扩展名
			String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(),
					file.getSize(), extension, null);
			return baseUrl + storePath.getFullPath();
		} catch (IOException e) {
			// TODO: handle exception
			log.error("文件上传失败...{}", e);
//			throw new RuntimeException("文件上传失败..." + e.getMessage());
			return "文件上传失败..." + e.getMessage();
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param category
	 * @param author
	 * @return
	 */
	public String uploadFile(MultipartFile file, String category, String author) {
		// Parameters:inputStream fileSize fileExtName metaDataSet
		String ext = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
		try {
			StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
			FileEntity fileEntity = new FileEntity();
			fileEntity.setType(ext);
			fileEntity.setName(file.getOriginalFilename());
			String url = baseUrl + storePath.getFullPath();
			fileEntity.setUrl(url);
			fileEntity.setCategoryId(category);
			fileEntity.setAuthor(author);
			fileMapper.saveFile(fileEntity);
			return url;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "文件上传失败..." + e.getMessage();
		}

	}

}
